import path from 'node:path'
import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
import { g_pkg } from './scripts/utils.js'
import json from '@rollup/plugin-json'
import esbuild from 'rollup-plugin-esbuild'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import chalk from 'chalk'

if (!process.env.TARGET) {
  throw new Error('TARGET 包必须通过 --environment 标志指定。')
}

const require = createRequire(import.meta.url)
const __dirname = fileURLToPath(new URL('.', import.meta.url))

const packagesDir = path.resolve(__dirname, g_pkg.targetsDir)
const packageDir = path.resolve(packagesDir, process.env.TARGET)

const resolve = p => path.resolve(packageDir, p)
const pkg = require(resolve(`package.json`))
const packageOptions = pkg.buildOptions || {}
const name = path.basename(packageDir)
console.log(name,  packageOptions.name, 66666)
const outputOptions = {
  "esm-bundler": {
    file: resolve(`dist/${name}.esm-bundler.js`),
    format: 'es'
  },
  "cjs": {
    file: resolve(`dist/${name}.cjs.js`),
    format: 'cjs'
  },
  "global": {
    file: resolve(`dist/${name}.global.js`),
    format: 'iife'
  },
}
function createConfig(format, output) {
  if (!output) {
    console.log(chalk.yellow(`invalid format: "${format}"`))
    process.exit(1)
  }

  const isGlobalBuild = /global/.test(format)
  if (isGlobalBuild) {
    output.name = packageOptions.name
  }

  output.sourcemap = process.env.SOURCE_MAP
  
  return {
    input: resolve('src/index.ts'),
    output,
    plugins: [
      json(),
      esbuild({
        tsconfig: path.resolve(__dirname, 'tsconfig.json'),
        // sourceMap: output.sourcemap,
        minify: false,
        target: 'es2015',
      }),
      nodeResolve()
    ],
  }
}
export default packageOptions.formats.map(format => createConfig(format, outputOptions[format]))